package org.csu.mybigpro.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class VirtualStudentService {

    @Autowired
    private AiService aiService;

    @Autowired
    private RestTemplate restTemplate;

    @Value("${livekit.api.key}")
    private String livekitApiKey;

    @Value("${livekit.api.secret}")
    private String livekitApiSecret;

    @Value("${livekit.url}")
    private String livekitUrl;

    private final List<VirtualStudent> students = Arrays.asList(
            new VirtualStudent("小明", "积极提问型"),
            new VirtualStudent("小红", "容易走神型"),
            new VirtualStudent("小刚", "基础薄弱型")
    );

    private final ObjectMapper objectMapper = new ObjectMapper();

    public void processTeacherSpeech(String roomName, String lessonContext, String teacherTranscript) {
        // ======================= 【修改点】 =======================
        // 如果识别结果为空或只有空白，则直接返回，不进行任何处理
        if (teacherTranscript == null || teacherTranscript.isBlank()) {
            return;
        }
        // ==========================================================

        System.out.println("接收到教师语音: " + teacherTranscript);

        for (VirtualStudent student : students) {
            if (student.shouldSpeak(teacherTranscript)) {
                System.out.println(student.getName() + " 决定发言...");

                String response = aiService.generateVirtualStudentResponse(
                        student.getPersonality(),
                        lessonContext,
                        teacherTranscript
                );

                if (response != null && !response.isBlank()) {
                    sendDataMessage(roomName, student.getName(), response);
                }
            }
        }
    }

    private void sendDataMessage(String roomName, String studentName, String message) {
        try {
            String token = createApiToken(roomName);

            Map<String, Object> chatPayload = Map.of(
                    "type", "ai_student_chat",
                    "from", studentName,
                    "message", message
            );
            String chatDataJson = objectMapper.writeValueAsString(chatPayload);
            String base64Data = java.util.Base64.getEncoder().encodeToString(chatDataJson.getBytes(StandardCharsets.UTF_8));

            Map<String, Object> requestBodyMap = Map.of(
                    "room", roomName,
                    "data", base64Data,
                    "kind", 1
            );
            String jsonBody = objectMapper.writeValueAsString(requestBodyMap);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.setBearerAuth(token);

            HttpEntity<String> entity = new HttpEntity<>(jsonBody, headers);
            String apiUrl = livekitUrl.replaceFirst("ws", "http") + "/twirp/livekit.RoomService/SendData";

            System.out.printf("正在通过 REST API 发送消息到 %s ...%n", apiUrl);
            restTemplate.postForEntity(apiUrl, entity, String.class);
            System.out.println("消息发送成功!");

        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("通过 REST API 发送消息失败: " + e.getMessage());
        }
    }

    private String createApiToken(String roomName) {
        Map<String, Object> videoGrant = Map.of(
                "roomAdmin", true,
                "room", roomName
        );

        return Jwts.builder()
                .setIssuer(livekitApiKey)
                .setSubject(livekitApiKey)
                .setIssuedAt(Date.from(Instant.now()))
                .setExpiration(Date.from(Instant.now().plusSeconds(60)))
                .claim("video", videoGrant)
                .signWith(Keys.hmacShaKeyFor(livekitApiSecret.getBytes(StandardCharsets.UTF_8)), SignatureAlgorithm.HS256)
                .compact();
    }

    static class VirtualStudent {
        private final String name;
        private final String personality;

        public VirtualStudent(String name, String personality) {
            this.name = name;
            this.personality = personality;
        }

        public String getName() { return name; }
        public String getPersonality() { return personality; }

        public boolean shouldSpeak(String transcript) {
            if (transcript.contains("有没有同学知道") || transcript.contains("谁来回答一下") || transcript.contains("明白吗")) {
                if ("积极提问型".equals(personality)) return Math.random() < 0.8;
                if ("基础薄弱型".equals(personality)) return Math.random() < 0.2;
            }
            if ("容易走神型".equals(personality)) {
                if (transcript.contains("重点") || transcript.contains("注意听") || transcript.contains("考试会考")) {
                    return Math.random() < 0.6;
                }
                return Math.random() < 0.3;
            }
            if("基础薄弱型".equals(personality)) {
                if(transcript.contains("推导") || transcript.contains("微积分") || transcript.contains("拉格朗日")) {
                    return Math.random() < 0.7;
                }
            }
            return Math.random() < 0.5;
        }
    }
}